package cn.itcast.service.impl;

import cn.itcast.mapper.ClazzMapper;
import cn.itcast.mapper.StudentMapper;
import cn.itcast.pojo.Clazz;
import cn.itcast.pojo.ClazzQueryParam;
import cn.itcast.pojo.PageResult;
import cn.itcast.service.ClazzService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StudentMapper studentMapper;
    @Override
    public void save(Clazz clazz) {

        //添加基础数据
        LocalDateTime now = LocalDateTime.now();
        clazz.setCreateTime(now);
        clazz.setUpdateTime(now);
        clazzMapper.insert(clazz);


    }

    @Override
    public List<Clazz> findAll() {
        List<Clazz> clazzList = clazzMapper.findAll();
        return clazzList;
    }

    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {
        //1.使用分页插件
        PageHelper.startPage(clazzQueryParam.getPage(),clazzQueryParam.getPageSize());
        //2.获取查询结果
        List<Clazz> clazzList = clazzMapper.page(clazzQueryParam);
        //3.转成Page<Clazz>
        Page<Clazz> clazzPage = (Page<Clazz>) clazzList;
        //4.封装到PageResult
        PageResult<Clazz> build = PageResult.<Clazz>builder().rows(clazzPage.getResult()).total(clazzPage.getTotal()).build();
        return build;
    }

    @Override
    public Clazz findById(Integer id) {

        return clazzMapper.findById(id);
    }

    @Override
    public void updateClazz(Clazz clazz) {
        clazzMapper.updateClazz(clazz);
    }

    @Override
    public void deleteById(Integer id) {

        //判断这个班级是否有人，如果有人，不删除，无人，直接删除
        Integer count = studentMapper.countByClazzId(id);
        if (count==0){
            clazzMapper.deleteById(id);
        }else {
            throw new RuntimeException("班级人数不为0，不能删除");
        }




    }
}
